package com.yiboshi.rehrs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.helper.RedisHelper;
import com.yiboshi.rehrs.manager.ZhongYouManager;
import com.yiboshi.rehrs.param.CallRecord;
import com.yiboshi.rehrs.param.ZhongRes;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @author jack 2025/2/8
 */
@Slf4j
@RestController
@RequestMapping("/zh_you")
public class ApiInsideController {

    //

    @Autowired
    RedisHelper redisHelper;

    @Autowired
    ZhongYouManager zhongYouManager;

    @Autowired
    IZhongUserService zhongUserService;
    //https://211.156.197.65/pdalogin/p/common/ticketvalidator
    @PostMapping("/ticketvalidator/{account}")
    public ZhongRes ticketvalidator(@PathVariable String account) {
        ZhongUser zhongUser = getTaskZhongUser(account);
        JSONObject jsonObject = zhongYouManager.ticketvalidator(zhongUser,null);
        return ZhongRes.ok(jsonObject);
    }
//https://211.156.197.65/pdalogin/p/common/noTokenAccessSendAuthCodeByUsr
    @PostMapping("/pdalogin/p/common/noTokenAccessSendAuthCodeByUsr")
    public ZhongRes noTokenAccessSendAuthCodeByUsr(@PathVariable String account) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("person_no","2153011500166");
        jsonObject = zhongYouManager.noTokenAccessSendAuthCodeByUsr(jsonObject);
        return ZhongRes.ok(jsonObject);
    }



    @NotNull
    private ZhongUser getTaskZhongUser(String account) {
        ZhongUser zhongUser = zhongUserService.one(account);
        zhongUser.setToken(redisHelper.loadTaskToken(account));
        return zhongUser;
    }

    @PostMapping("/findpdasignWaybillinfoNew/{account}")
    public ZhongRes findpdasignWaybillinfoNew(@PathVariable String account) {
        ZhongUser zhongUser = getTaskZhongUser(account);
        JSONArray jsonArray = zhongYouManager.findpdasignWaybillinfoNew(zhongUser,null);
        return ZhongRes.ok(jsonArray);
    }

    @PostMapping("/queryWaybill/{account}")
    public ZhongRes queryWaybill(@PathVariable String account, @RequestParam  String waybillNo) {
        ZhongUser zhongUser = getTaskZhongUser(account);
        JSONObject jsonObject = zhongYouManager.queryWaybill(zhongUser, waybillNo);
        return ZhongRes.ok(jsonObject);
    }


    @PostMapping("/updatephone/{account}")
    public ZhongRes updatephone(@PathVariable String account, @RequestParam  String waybillNo, @RequestParam String phoneNum) {
        ZhongUser zhongUser = getTaskZhongUser(account);
        boolean b = zhongYouManager.updatePhone(zhongUser, waybillNo, phoneNum);
        return ZhongRes.ok();
    }

    //https://211.156.197.65/pdalogin/p/common/changesubstitutionorg
    @PostMapping("/changesubstitutionorg/{account}")
    public ZhongRes changesubstitutionorg(@PathVariable String account,@RequestParam String substitutionorg)  {
        ZhongUser zhongUser = getTaskZhongUser(account);
        boolean b = zhongYouManager.changesubstitutionorg(zhongUser, substitutionorg);
        return ZhongRes.ok();
    }

    @PostMapping("/traceInfo/query/{account}")
    public ZhongRes traceInfoQuery(@PathVariable String account, @RequestParam  String waybillNo)  {
        ZhongUser zhongUser = getTaskZhongUser(account);
        JSONObject jsonObject = zhongYouManager.traceInfoQuery(zhongUser, waybillNo);
        return ZhongRes.ok(jsonObject);
    }


//https://211.156.197.65/delivery-app/p/pdasignwaybillFeedback/singleDeliver
    @PostMapping("/singleDeliver/{account}")
    public ZhongRes singleDeliver(@PathVariable String account, @RequestParam  String waybillNo)  {
        ZhongUser zhongUser = getTaskZhongUser(account);
        JSONObject jsonObject = zhongYouManager.singleDeliver(zhongUser, waybillNo);
        return ZhongRes.ok(jsonObject);
    }



    @PostMapping("/newCallAndFile/{account}")
    public ZhongRes newCallAndFile(@PathVariable String account, @RequestParam  String waybillNo, @RequestParam String phoneNum) {
        ZhongUser zhongUser = getTaskZhongUser(account);
        CallRecord callFile = new CallRecord();
        int time = 25+AperStringUtils.randomNum(20);
        callFile.setCallTime(DateUtils.dateTimeToStr(LocalDateTime.now(),DateUtils.SQL_TIME));
        callFile.setTalkTime(time+"秒");//大象没有秒 金蛇有秒 zy有秒
        callFile.setWaybillNo(waybillNo);
        callFile.setMobile(phoneNum);
        //callFile.setTypeFlag("1");
        callFile.setInFlag("3");
        if(phoneNum.length()>12){
            callFile.setWhetherAllowRecording("1");
        }else{
            callFile.setWhetherAllowRecording("0");
        }
        callFile.setIsConnect("1");
        boolean b = zhongYouManager.newCallAndFile(zhongUser, callFile);
        return ZhongRes.ok();
    }











  /*  @ApiOperation(value = "1.0 logon", httpMethod = "POST", notes = "1.0 档案首页基本信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/{path}")
   *//* @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "residentId", value = "residentId", required = true, dataType = "Long")
    })*//*
    public ResVO logon(@PathVariable String path,@RequestBody ReqVO modelVO){
        Integer type = modelVO.getType();
        if(type==null){
            type = 1;
        }
        String data = modelVO.getData();
        if(data.contains("init_login")){//首次初始化
            data = data+"&imei="+"CPUR48A237000551";
        }
        if(!data.contains("time")){
            data = data+"&time="+(System.currentTimeMillis()-28800);
        }

        modelVO.setType(type);
        modelVO.setData(data);
        return null;


        //return post;
    }*/


    String xiaofeixia_logon_url = "http://u.xiaofeixiakeji.cn/api/user/1000/android/5.0.4/logon";

    String daxiang_login_url = "http://121.62.30.239:2025/api/user/1000/android/5.1.3/logon";

    String xiaofeixia_vip_account = "account=2153011500151&password=fakepasswd&udid=2153011500151&type=loginbyusrsms&imei=867382035888381&time=";
    String xiaofeixia_vip_face = "account=2153011500151&password=fakepasswd&udid=2153011500151&type=loginbyusrface&imei=867382035888381&time=";
/*

    //金蛇登录
    @ApiOperation(value = "1.0 logon", httpMethod = "POST", notes = "1.0 档案首页基本信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/js/logon")
    public ResVO js_logon(@RequestBody () ReqVO modelVO) throws Exception {
        modelVO.setType(3);
        String data = modelVO.getData();
        Map<String, String> map = CommonUtil.toQueryMap(data);
        //data = data+"&time="+(System.currentTimeMillis()/1000);
        String account = map.get("account");
        UserInfo userCache = getUserCache(account);
        if(userCache!=null){
            log.info("缓存登录，{}",account);
            ResVO resVO = new ResVO();
            JSONObject u_info = JSONBuilder.start("u_info", userCache).end();
            resVO.setJsonObjectData(u_info);
            return resVO;
        }
        String md5 = MD5.create().digestHex16(account);

        modelVO.setData(data);
        //String token = JinsheUtil.token(account);
        //String logon = jinsheFeign.post("logon", modelVO);
        //JSONObject jsonObject = JSONObject.parseObject(logon);
        //String token = jsonObject.getString("token");
        //data = "token=%s&time=%d&path=%s&pp=HONOR&xh=AQM-AL10&lx=0&qi5uxeel=";
        //String format = String.format(data, token, System.currentTimeMillis() / 1000, VarConstant.zy_face_logon_url);
        //modelVO.setData(format);

        //String zyltlogin = jinsheFeign.post("zyltlogin", modelVO);
        String token = JinsheUtil.token(account);
        String qi5uxeel = JinsheUtil.loginKey(token,account, VarConstant.zy_face_logon_url);
        if(StrUtils.isBlank(qi5uxeel)){
            return ResVO.fail;
        }
        Long currentTimeMillis = System.currentTimeMillis();
        JSONBuilder z_info = JSONBuilder.start("time", currentTimeMillis)
                .put("jdpt_sign", HeaderHelper.jdpt_sign(currentTimeMillis.toString(),"",account))
                .put("qi5uxeel", JSONBuilder.start("qi5uxeel", qi5uxeel).end())
                .put("account", account)
                .put("pda_id", "869296041015581");
        token = new StringBuilder(token).reverse().toString();
        JSONBuilder u_info = JSONBuilder.start("token", token).put("type",3);
        JSONObject jsonObject = JSONBuilder.start("z_info", z_info)
                .put("u_info", u_info)
                .end();
        ResVO resVO = new ResVO();
        resVO.setJsonObjectData(jsonObject);
        return resVO;
    }

    @ApiOperation(value = "1.0 logon", httpMethod = "POST", notes = "1.0 档案首页基本信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/vip")
   */
/* @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "residentId", value = "residentId", required = true, dataType = "Long")
    })*//*

    public ResVO vip(@RequestBody () ReqVO modelVO, HttpServletRequest request) throws Exception {
        String data = modelVO.getData();
        Map<String, String> map = CommonUtil.toQueryMap(data);
        String user_token = map.get("token");
        String type = map.get("type");
        UserInfo userCache = getUserCache(user_token);
        String pda_user_token = userCache.getPda_user_token();
        String vipTokenCache = vipHelper.getVipTokenCache(modelVO.getType());
        ResVO vipRes = null;
        if(modelVO.getType().equals(3)){
            String qi5uxeel = JinsheUtil.loginKey(vipTokenCache, "", map.get("path"));
            Long currentTimeMillis = System.currentTimeMillis();
            String person_no = userCache.getPerson_no();
            JSONBuilder z_info = JSONBuilder.start("time", currentTimeMillis+"")
                    .put("jdpt_sign", HeaderHelper.jdpt_sign(currentTimeMillis.toString(),pda_user_token,person_no))
                    .put("qi5uxeel", JSONBuilder.start("qi5uxeel", qi5uxeel).end())
                    .put("account", person_no)
                    .put("pda_user_token",pda_user_token)
                    .put("pda_id", "867382035888381");
            JSONBuilder u_info = JSONBuilder.start("token", user_token).put("type",3);
            JSONObject jsonObject = JSONBuilder.start("z_info", z_info)
                    .put("u_info", u_info)
                    .end();

            vipRes  = new ResVO();
            vipRes.setJsonObjectData( z_info.end());
        }else{
            vipRes = VipHelper.vip(pda_user_token, vipHelper.getVipTokenCache(1), type);
        }
       // ResVO vipRes2 =VipHelper.vip(pda_user_token, vipHelper.getVipTokenCache(1), type);

        //vipTokenCache = userCache.getToken();

       // System.out.println(JSONUtil.toJsonPrettyStr(vipRes.getJsonObjectData()));
       // System.out.println(JSONUtil.toJsonPrettyStr(vipRes2.getJsonObjectData()));


     */
/* String api = "http://211.156.197.65/delivery-app/p/delivery/pdataskquery/findpdasignwaybillinfonew.do";
        JSONObject jsonObject = JSON.parseObject("{\"waybillState\":\"2\",\"pageNo\":\"\",\"waybillNo\":\"\",\"businessProductCode\":\"\",\"importRegionDate\":\"\",\"dlvState\":\"\",\"orderTag\":\"1\",\"queryType\":\"\"}");
        MapBuilder<String, String> byXfx = HeaderHelper.createByXfx(vipRes.getJsonObjectData());
        JSONObject jsonObject1 = HttpClientUtils.doJsonPost(api, byXfx.end(), jsonObject);
        log.info("jsonObject1:{}",jsonObject1);*//*

        // String dataNew = data.replace(token, vipTokenCache).replace(pda_user_token,pda_token);
        //String format = String.format(vipUrl, u_vip_token, zy_token, type, System.currentTimeMillis());
        //ResVO vipRes = XiaofeixiaFeign.post(1, "vip", new ReqVO(dataNew));
        return vipRes;
    }

    @ApiOperation(value = "1.0 logon", httpMethod = "POST", notes = "1.0 档案首页基本信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/logonBack")
   */
/* @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "residentId", value = "residentId", required = true, dataType = "Long")
    })*//*

    public ResVO logonBack(@RequestBody () UserInfo userinfo, HttpServletRequest request) {
        log.info("logonBack-userinfo:{}", JSON.toJSONString(userinfo));
        String token = userinfo.getToken();
        //ThrowExceptionUtils.throwBusinessException(StrUtils.isBlank(token),"登录失败");
        if(StrUtils.isNotBlank(userinfo.getPda_user_token())){
            userinfo.setPda_user_token(userinfo.getPda_user_token());
            userinfo.setPerson_name(userinfo.getPerson_name());
            userinfo.setSimple_name_cn(userinfo.getSimple_name_cn());
            String key = "a:user:"+userinfo.getPerson_no()+":"+token;
            redisTemplate.opsForValue().set(key,userinfo,2, TimeUnit.HOURS);
            return ResVO.ok;
        }
        //token = new StringBuilder(token).reverse().toString();
        //ResVO logout = JinsheUtil.logout(token);
        //log.info("logonBack-logout:{}，token：{}", JSON.toJSONString(logout),token);
        return ResVO.fail;

    }
*/


    public static MapBuilder buildHeader(JSONObject jsonObject) {
        MapBuilder mapBuilder = MapBuilder.start();
        String jdpt_sign = jsonObject.getString("jdpt_sign");
        String jdpt_req_time = jsonObject.getString("time");
        String person_no = jsonObject.getString("account");

        String qi5uxeel = jsonObject.getJSONObject("qi5uxeel").getString("qi5uxeel");

        //if (Intrinsics.areEqual("B", "B")) {
        //jdpt_sign = getSHA256("jdpt_req_time=" + currentTimeMillis + "&pda_user_token=" + pda_user_token + "&person_no=" + person_no + "&thirdKey=DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9", "DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9");
//        } else {
//            jdpt_sign = SHA256Util.getSHA256("dev_id=" + loadString3 + "&jdpt_req_time=" + currentTimeMillis + "&pda_user_token=" + loadString + "&person_no=" + loadString2 + "&thirdKey=DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9", "DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9");
//        }
        // HttpCommonInterceptor.Builder builder = new HttpCommonInterceptor.Builder();
        mapBuilder.put("Connection", "Keep-Alive");
        mapBuilder.put("Cookie", "CORAL_GRAYLEVEL=0");
        //mapBuilder.put("Host", "211.156.197.65");
        mapBuilder.put("algorithm_flag", "B");
        mapBuilder.put("dlv_equipment_type", "Newland");
        mapBuilder.put("jdpt_req_time", jdpt_req_time);
        mapBuilder.put("jdpt_sign", jdpt_sign);
        mapBuilder.put("pda_id", "869296041015581");
        mapBuilder.put("android_id", "869296041015581");

        mapBuilder.put("pda_sys", "Android");
        mapBuilder.put("pda_sys_version", "12");
        mapBuilder.put("pda_type", "A");
        mapBuilder.put("pda_version", "244");
        mapBuilder.put("pda_user_token", "");
        mapBuilder.put("person_no", person_no);
        mapBuilder.put("qi5uxeel", qi5uxeel);
        mapBuilder.put("safe_id", "ISRS");
        mapBuilder.put("user-agent", "Dalvik/2.1.0 (Linux; U; Android 9; Pixel Build/PQ3A.190801.002)");
        mapBuilder.put("version_name", "1.4.6");
        //mapBuilder.put("Accept-Encoding", "gzip");
        return mapBuilder;
    }

    public void setUserCache(String acount_token) {

    }




    private static String getSHA256(String s, String s1) {
        return SHA256Util.getSHA256(s, s1);
    }


}
